package com.p2l.letterblocks;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ActivityWardrobe extends Activity {
	private static Item[] clothes;
	private static BearView view;
	private static Bitmap bear;
	private static Rect dst;

	private SharedPreferences preferences;
	private SwipeAdapter adapter;
	private LinearLayout background;
	private ViewPager pager;
	private TextView spinner;
	private Context context;
	private Button clear, save;
	
	private SQLiteDatabase sqlite;
	private Database db;
	
	private ArrayList<Item> items;
	private String[] keys;;
	private String[] groups;
	private Item[][] sorted;
	
	private float size;
	private int userId, selected;
	
	private OnClickListener listener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Item item = (Item) v.getTag();
			Drawable[] layers = new Drawable[2];
			layers[0] = getResources().getDrawable(R.drawable.item_background);
			layers[1] =(item.getType() == Item.COINS ? getResources().getDrawable(item.getCoin_picture()) : new BitmapDrawable(getResources(), item.getShopBitmap()));
			LayerDrawable layer = new LayerDrawable(layers);
			
			if (item == clothes[item.getType()]) {
				layers[1] = new BitmapDrawable(getResources(), item.getShopBitmap());
				layer = new LayerDrawable(layers);
				v.setBackgroundDrawable(layer);
				clothes[item.getType()] = null;
			} else {
				boolean found = false;
				int i = 0;
				while (!found && i < sorted[selected].length) {
					if (sorted[selected][i] == clothes[item.getType()])
						found = true;
					else
						i++;
				}
				if (found) {
					int index = (int)(i / 9);
					int n = (int)((i % 9) / 3);
					LinearLayout page = (LinearLayout) pager.getChildAt(index);
					LinearLayout layout = (LinearLayout) page.getChildAt(n);
					View view = layout.getChildAt(i % 3);
					
					layers[1] = (clothes[item.getType()].getType() == Item.COINS ? getResources().getDrawable(clothes[item.getType()].getCoin_picture()) : new BitmapDrawable(getResources(), clothes[item.getType()].getShopBitmap()));
					layer = new LayerDrawable(layers);
					view.setBackgroundDrawable(layer);
				}
				layers[0] = getResources().getDrawable(R.drawable.item_background_selected);
				layers[1] = (item.getType() == Item.COINS ? getResources().getDrawable(item.getCoin_picture()) : new BitmapDrawable(getResources(), item.getShopBitmap()));
				layer = new LayerDrawable(layers);
				layer = new LayerDrawable(layers);
				v.setBackgroundDrawable(layer);
				clothes[item.getType()] = item;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.wardrobe);
		
		System.gc();
		
		keys = getResources().getStringArray(R.array.keys);
		groups = getResources().getStringArray(R.array.groups);
		size = getResources().getDimension(R.dimen.shop_prize);
		userId = getIntent().getIntExtra("userId", -1);
		selected = 0;
		
		context = this;
		bear = BitmapFactory.decodeResource(getResources(), R.drawable.wardrobe_bear);
		clothes = new Item[5];
		preferences = getSharedPreferences("LetterBlocks", MODE_PRIVATE);

		view = (BearView) findViewById(R.id.imgBear);
		view = new BearView(this);
		
		dst = new Rect(0, 0, 0, 0);
		items = new ArrayList<Item>();
		sorted = new Item[][] { new Item[0], new Item[0], new Item[0], new Item[0], new Item[0], new Item[0] };
		
		background = (LinearLayout) findViewById(R.id.wardrobe_background);
			
		clear = (Button) findViewById(R.id.btnWardrobeClear);
		clear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				for (int i = 0; i < clothes.length; i++)
					clothes[i] = null;
				
				clearPager();
				adapter = new SwipeAdapter();
				pager = (ViewPager) findViewById(R.id.pager);
				pager.setAdapter(adapter);
			}
		});
		
		save = (Button) findViewById(R.id.btnSave);
		save.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Editor editor = preferences.edit();
				for (int i = 0; i < clothes.length; i++) {
					editor.putInt(keys[i], (clothes[i] == null ? -1 : clothes[i].getId()));
					editor.putString("string_" + keys[i], (clothes[i] == null ? "" : clothes[i].getName()));
				}
				editor.putInt("userId", userId);
				editor.commit();
				finish();
			}
		});

		spinner = (TextView) findViewById(R.id.spinner1);
		spinner.setText(groups[selected]);
		spinner.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DialogItem dialog = new DialogItem(context, DialogItem.WARDROBE);
				dialog.show();
			}
		});

		db = new Database(context);
		sqlite = db.getWritableDatabase();
		getItems();

		clearPager();
		adapter = new SwipeAdapter();
		pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(adapter);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		
		for (int i = 0; i < sorted.length; i++) {
			for (int j = 0; j < sorted[i].length; j++) {
				sorted[i][j] = null;
			}
			sorted[i] = null;
		}
		sorted = null;
		
		for (int i = 0; i < clothes.length; i++)
			clothes[i] = null;
		
		for (int i = 0; i < items.size(); i++) {
			Item item = items.get(i);
			if (item.getWardropeBitmap() != null)
				item.getWardropeBitmap().recycle();
			if (item.getGameBitmap() != null)
				item.getGameBitmap().recycle();
			if (item.getShopBitmap() != null)
				item.getShopBitmap().recycle();
		}
		
		if (bear != null)
			bear.recycle();
		
		if (background.getBackground() != null)
			background.getBackground().setCallback(null);
		
		if (spinner.getBackground() != null)
			spinner.getBackground().setCallback(null);
		
		if (clear.getBackground() != null)
			clear.getBackground().setCallback(null);
		
		if (save.getBackground() != null)
			save.getBackground().setCallback(null);
		
		clearPager();
		items.clear();
		
		preferences = null;
		background = null;
		listener = null;
		adapter = null;
		spinner = null;
		context = null;
		clothes = null;
		groups = null;
		sorted = null;
		pager = null;
		clear = null;
		items = null;
		bear = null;
		view = null;
		save = null;
		keys = null;
		dst = null;
		
		db.close();
		db = null;
		sqlite = null;

		System.gc();
	}
	
	public void onItemGroupChanged(int position) {
		selected = position;
		spinner.setText(groups[selected]);
		clearPager();
		adapter = new SwipeAdapter();
		pager = (ViewPager) findViewById(R.id.pager);
		pager.setAdapter(adapter);
	}
	
	private void clearPager() {
		if (pager != null) {
			LinearLayout l = (LinearLayout) pager.getChildAt(0);
			for (int i = 0; i < l.getChildCount(); i++) {
				if (i == l.getChildCount()) {
					l.removeView(l.getChildAt(i));
				} else {
					LinearLayout layout = (LinearLayout) l.getChildAt(i);
					for (int j = 0; j < layout.getChildCount(); j++) {
						if (layout.getChildAt(j) instanceof TextView) {
							TextView t = (TextView) layout.getChildAt(j);
							t.getBackground().setCallback(null);
							layout.removeView(t);
							t = null;
						} else if (layout.getChildAt(j) instanceof ProgressBar) {
							ProgressBar bar = (ProgressBar) layout.getChildAt(j);
							layout.removeView(bar);
							bar = null;
						}
					}
					l.removeView(layout);
					layout = null;
				}
			}
			pager.removeView(l);
			l = null;
		}
	}

	// swipe adapter to swipe between the items
	private class SwipeAdapter extends PagerAdapter {
		@Override
		public Object instantiateItem(ViewGroup collection, int position) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
			params.weight = 1;
			
			LinearLayout l1 = new LinearLayout(context);
			l1.setOrientation(LinearLayout.VERTICAL);
			l1.setLayoutParams(params);
			
			for (int i = 0; i < 3; i++) {
				LinearLayout l2 = new LinearLayout(context);
				l2.setOrientation(LinearLayout.HORIZONTAL);
				l2.setLayoutParams(params);
				for (int j = 0; j < 3; j++) {
					int index = (i * 3) + j + (position * 9);
					if (index < sorted[selected].length) {
						Item item = sorted[selected][index];
						if (item.getShopBitmap() != null && item.getWardropeBitmap() != null) {// && item.getGameBitmap() != null) {
							Drawable[] layers = new Drawable[2];
							layers[0] = (item == clothes[item.getType()] ? getResources().getDrawable(R.drawable.item_background_selected) : getResources().getDrawable(R.drawable.item_background));
							layers[1] = new BitmapDrawable(getResources(), item.getShopBitmap());
							LayerDrawable layer = new LayerDrawable(layers);
							
							TextView txt = new TextView(context);
							txt.setLayoutParams(params);
							txt.setBackgroundDrawable(layer);
							txt.setTag(item);
							txt.setOnClickListener(listener);
							l2.addView(txt);
						} else {
							ProgressBar p = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge);
							p.setBackgroundResource(R.drawable.item_background);
							p.setLayoutParams(params);
							l2.addView(p);
							new DownloadBitmapTask().execute(i, j, position, selected);
						}
					} else {
						TextView txt = new TextView(context);
						txt.setBackgroundResource(R.drawable.item_background);
						txt.setLayoutParams(params);
						l2.addView(txt);
					}
				}
				l1.addView(l2);
			}
			TextView t = new TextView(context);
			t.setText((position + 1) + "/" + getCount());
			t.setGravity(Gravity.CENTER);
			t.setTextSize(size);
			t.setTextColor(Color.BLACK);
			t.setTypeface(Typeface.DEFAULT_BOLD);
			l1.addView(t);
			
			collection.addView(l1);
			return l1;
		}
		
		@Override
		public void destroyItem(ViewGroup collection, int position, Object view) {
			collection.removeView((LinearLayout) view);
		}
		
		@Override
		public int getCount() {
			int count = 0;
			int size = sorted[selected].length;
			count = (int)(size / 9) + (size % 9 == 0 ? 0 : 1);
			return (count == 0 ? 1 : count);
		}

		@Override
		public boolean isViewFromObject(View v, Object o) {
			return v == o;
		}
	}
	
	private void getItems() {
		int savedId = preferences.getInt("userId", -1);
		int[] ids = new int[5];
		if (savedId == userId) {
			for (int i = 0; i < ids.length; i++)
				ids[i] = preferences.getInt(keys[i], -1);
		}
		
		ArrayList<Item> hats, shirts, pants, shoes, accessories;
		hats = new ArrayList<Item>();
		shirts = new ArrayList<Item>();
		pants = new ArrayList<Item>();
		shoes = new ArrayList<Item>();
		accessories = new ArrayList<Item>();
		
		String select = "SELECT TB_items.itemId, TB_items.name, TB_items.type, TB_items.price";
		String where = " WHERE TB_item_transactions.userId='" + userId + "'";
		String join = " LEFT JOIN TB_item_transactions ON TB_items.itemId = TB_item_transactions.itemId";
		Cursor cursor = db.select(sqlite, select, Database.TABLE_NAME_ITEMS, join, where);
		items = db.getItems(cursor);
		
		for (Item item : items) {
			switch (item.getType()) {
			case Item.HATS:
				hats.add(item);
				break;
			case Item.SHIRTS:
				shirts.add(item);
				break;
			case Item.PANTS:
				pants.add(item);
				break;
			case Item.SHOES:
				shoes.add(item);
				break;
			case Item.ACCESSORIES:
				accessories.add(item);
				break;
			}
		}
		sorted[0] = new Item[items.size()];
		for (int i = 0; i < items.size(); i++)
			sorted[0][i] = items.get(i);
		
		sorted[1] = new Item[hats.size()];
		for (int i = 0; i < hats.size(); i++)
			sorted[1][i] = hats.get(i);
		
		sorted[2] = new Item[shirts.size()];
		for (int i = 0; i < shirts.size(); i++)
			sorted[2][i] = shirts.get(i);
		
		sorted[3] = new Item[pants.size()];
		for (int i = 0; i < pants.size(); i++)
			sorted[3][i] = pants.get(i);
		
		sorted[4] = new Item[shoes.size()];
		for (int i = 0; i < shoes.size(); i++)
			sorted[4][i] = shoes.get(i);
		
		sorted[5] = new Item[accessories.size()];
		for (int i = 0; i < accessories.size(); i++)
			sorted[5][i] = accessories.get(i);
		
		
		for (int i = 0; i < items.size(); i++) {
			Item item = items.get(i);
			Bitmap wardrobe = Server.loadBitmap(context, Server.FOLDERS[item.getType()], item.getName() + "_wardrobe.png");
			Bitmap shop = Server.loadBitmap(context, Server.FOLDERS[item.getType()], item.getName() + "_shop.png");
			//Bitmap game = Server.loadBitmap(context, Server.FOLDERS[item.getType()], item.getName() + "_game.png");
			item.setWardropeBitmap(wardrobe);
			item.setShopBitmap(shop);
			//item.setGameBitmap(game);
    		
			if (item.getId() == ids[item.getType()]) {
				clothes[item.getType()] = item;
			}
		}
		
		hats.clear();
		hats = null;
		shirts.clear();
		shirts = null;
		pants.clear();
		pants = null;
		shoes.clear();
		shoes = null;
		accessories.clear();
		accessories = null;
		select = null;
		where = null;
		join = null;
		cursor = null;
		ids = null;
	}
	
	// download task to download missing pictures from the server
	private class DownloadBitmapTask extends AsyncTask<Integer, Void, Boolean> {
		private Item item;
		
		private int row, column, page, group;
		
    	@Override
		protected Boolean doInBackground(Integer... params) {
    		try {
	    		row = params[0];
	    		column = params[1];
	    		page = params[2];
	    		group = params[3];
	    		item = sorted[selected][(row * 3) + column + (page * 9)];
	    		
	    		String folder = Server.FOLDERS[item.getType()];
				String name = item.getName();
	    		String url = "";
	    		InputStream in = null;

	    		/*if (item.getGameBitmap() == null) {
	    			url = Server.URL_HOME + Server.FOLDERS[item.getType()] + item.getName() + "_game.png";
	    			in = Server.open(url);
	    			Bitmap game = Server.downloadBitmap(in);
	    			item.setGameBitmap(game);
	    			if (game != null)
	    				Server.saveBitmap(context, folder, name + "_game.png", game);
	    		}*/
	    		if (item.getShopBitmap() == null) {
	    			url = Server.URL_HOME + Server.FOLDERS[item.getType()] + item.getName() + "_shop.png";
	    			in = Server.open(url);
		    		Bitmap shop = Server.downloadBitmap(in);
		    		item.setShopBitmap(shop);
		    		if (shop != null)
			    		Server.saveBitmap(context, folder, name + "_shop.png", shop);
		    		in.close();
	    		}
	    		if (item.getWardropeBitmap() == null) {
		    		url = Server.URL_HOME + Server.FOLDERS[item.getType()] + item.getName() + "_wardrobe.png";
		    		in = Server.open(url);
		    		Bitmap wardrobe = Server.downloadBitmap(in);
		    		item.setWardropeBitmap(wardrobe);
		    		if (wardrobe != null)
			    		Server.saveBitmap(context, folder, name + "_wardrobe.png", wardrobe);
		    		in.close();
	    		}
	    		folder = null;
	    		name = null;
	    		url = null;
	    		in = null;
	    		
	    		if (group == selected) {
		    		Activity a = (Activity) context;
		    		a.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							if (pager.getChildCount() > 0) {
								LinearLayout l =  (LinearLayout)((LinearLayout) pager.getChildAt(pager.getCurrentItem())).getChildAt(row);
					    		
								LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
								lp.weight = 1;
								
								Drawable[] layers = new Drawable[2];
								layers[0] = (item == clothes[item.getType()] ? getResources().getDrawable(R.drawable.item_background_selected) : getResources().getDrawable(R.drawable.item_background));
								layers[1] = new BitmapDrawable(getResources(), item.getShopBitmap());
								LayerDrawable layer = new LayerDrawable(layers);
					    		
								TextView txt = new TextView(context);
								txt.setLayoutParams(lp);
								txt.setBackgroundDrawable(layer);
								txt.setTag(item);
								txt.setOnClickListener(listener);
		
					    		l.removeViewAt(column);
					    		l.addView(txt, column);
							}
						}
		    		});
	    		}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				e.printStackTrace();
				return false;
			} catch (ArrayIndexOutOfBoundsException e) {
				e.printStackTrace();
				return false;
			}
    		
			return true;
		}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	item = null;
	    	this.cancel(true);
	    }
	}

	// custom view to draw the selected items on the bear
	private static class BearView extends ImageView {
		public BearView(Context context) {
			super(context);
		}
		
		public BearView(Context context, AttributeSet attrs) {
			super(context, attrs);
		}
		
		@Override
		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
			int width = MeasureSpec.getSize(widthMeasureSpec);
			int height = MeasureSpec.getSize(heightMeasureSpec);
			dst.right = width;
			dst.bottom = height;
		}
		
		@Override
		protected void onDraw(Canvas canvas) {
			// draw bear template
			if (bear != null)
				canvas.drawBitmap(bear, null, dst, null);
			
			// draw clothes on the bear
			for (int i = clothes.length - 3; i >= 0; i--)
				if (clothes[i] != null)
					if (clothes[i].getWardropeBitmap() != null)
						canvas.drawBitmap(clothes[i].getWardropeBitmap(), null, dst, null);
			
			// draw belt on the bear
			if (clothes[3] != null)
				if (clothes[3].getWardropeBitmap() != null)
					canvas.drawBitmap(clothes[3].getWardropeBitmap(), null, dst, null);
			
			// draw accessories on the bear
			if (clothes[4] != null)
				if (clothes[4].getWardropeBitmap() != null)
					canvas.drawBitmap(clothes[4].getWardropeBitmap(), null, dst, null);
			
			super.onDraw(canvas);
			invalidate();
		}
	}  
}

